﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Pantry.Entity;
using Pantry.Business;
using Pantry.Commons;

namespace Pantry.Web.Users.Controls
{
    public partial class ListRegion : System.Web.UI.UserControl
    {
        private readonly IFormatProvider _formatProvider = CultureInfo.CurrentCulture;
        private TrustRegionBus _trustRegionBus;
        private TrustRegion _trustRegion;
        private DataView _dataView;
        private static bool _isSorted;
        private static int _trustRegionId;
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadTrustRegion(CheckBoxIncludeInactive.Checked);
            Page.ClientScript.GetPostBackEventReference(this, string.Empty);
            if (IsPostBack)
            {
                string eventTarget = Request["__EVENTTARGET"] ?? string.Empty;
                string eventArgument = Request["__EVENTARGUMENT"] ?? string.Empty;
                switch (eventTarget)
                {
                    case "MyConfirmationPostBackEventTarget":
                        if (Convert.ToBoolean(eventArgument))
                        {
                            AfterUserConfirmationHandler();
                        }
                        break;
                }
            }
        }

        #region Methods

        /// <summary>
        /// Ham xu ly su kien sau khi user click ok trong confirm.
        /// </summary>
        private void AfterUserConfirmationHandler()
        {
            //Do your stuff here which you want to do when the user has confirmed the action
            if(_trustRegionId != 0)
            {
                _trustRegionBus = new TrustRegionBus();
                var result = _trustRegionBus.ChangeTrustRegionStatus(_trustRegionId, true);
                if (result)
                {
                    Response.Redirect("RegionDetail.aspx?TrustRegionId=" + _trustRegionId);
                }
            }
        }
        /// <summary>
        /// Loads the trust region.
        /// </summary>
        /// <param name="isIncludeInActive">if set to <c>true</c> [is include in active].</param>
        private void LoadTrustRegion(bool isIncludeInActive)
        {
            try
            {
                _trustRegionBus = new TrustRegionBus();
                DataSet dataSet = _trustRegionBus.SelectAll();
                _dataView = dataSet.Tables[0].DefaultView;
                if (!isIncludeInActive)
                {
                    _dataView.RowFilter = "IsActive = 'Yes'";
                }
                CollectionPager1.PageSize = 10;
                CollectionPager1.BindToControl = RepeaterTrustRegion;
                CollectionPager1.DataSource = _dataView;
                RepeaterTrustRegion.DataSource = CollectionPager1.DataSourcePaged;
                RepeaterTrustRegion.DataBind();
            }
            catch (FormatException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }

        }
        /// <summary>
        /// Sortings the specified field.
        /// </summary>
        /// <param name="field">The field.</param>
        private void Sorting(string field)
        {
            try
            {
                if (_isSorted)
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} DESC", field);
                    _isSorted = false;
                }
                else
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} ASC", field);
                    _isSorted = true;
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        /// <summary>
        /// Filters the trust region.
        /// </summary>
        /// <param name="isIncludeInActive">if set to <c>true</c> [is include in active].</param>
        /// <param name="filterString">The filter string.</param>
        private void FilterTrustRegion(bool isIncludeInActive, string filterString)
        {
            try
            {
                _trustRegionBus = new TrustRegionBus();
                DataSet dataSet = _trustRegionBus.SelectAll();
                _dataView = dataSet.Tables[0].DefaultView;
                string filterStatement = "";
                if (filterString.Length > -1)
                {
                    for (var i = 0; i < filterString.Length; i++)
                    {
                        if (i == (filterString.Length - 1))
                        {
                            if (!isIncludeInActive)
                            {
                                filterStatement += "TrustRegionName LIKE '" + filterString.Substring(i - 1, 1) +
                                                   "*') AND IsActive = 'Yes'";
                            }
                            else
                            {
                                filterStatement += "TrustRegionName LIKE '" + filterString.Substring(i - 1, 1) +
                                                   "*')";
                            }
                        }
                        else if (i == 0)
                        {
                            filterStatement += "(";
                        }
                        else
                        {
                            filterStatement += "TrustRegionName LIKE '" + filterString.Substring(i - 1, 1) +
                                               "*' OR ";
                        }
                    }
                    _dataView.RowFilter = filterStatement;
                }
                CollectionPager1.PageSize = 10;
                CollectionPager1.BindToControl = RepeaterTrustRegion;
                CollectionPager1.DataSource = _dataView;
                RepeaterTrustRegion.DataSource = CollectionPager1.DataSourcePaged;
                RepeaterTrustRegion.DataBind();
            }
            catch (ApplicationException ex)
            {
                ExceptionHandler.WriteErrorLog(ex);
            }
        }
        /// <summary>
        /// Removes the active on button.
        /// </summary>
        private void RemoveActiveOnButton()
        {
            LinkButton1.CssClass = "button-in-active";
            LinkButton2.CssClass = "button-in-active";
            LinkButton3.CssClass = "button-in-active";
            LinkButton4.CssClass = "button-in-active";
            LinkButton5.CssClass = "button-in-active";
            LinkButton6.CssClass = "button-in-active";
            LinkButton7.CssClass = "button-in-active";
            LinkButton8.CssClass = "button-in-active";
        }
        #endregion

        #region Event Handler
        /// <summary>
        /// Checks the box include inactive changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CheckBoxIncludeInactiveChanged(object sender, EventArgs eventArgs)
        {
            LoadTrustRegion(CheckBoxIncludeInactive.Checked);
        }
        /// <summary>
        /// Links the button trust name click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButtonTrustNameClick(object sender, EventArgs eventArgs)
        {
            Sorting("TrustRegionName");
        }
        /// <summary>
        /// Links the button description click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButtonDescriptionClick(object sender, EventArgs eventArgs)
        {
            Sorting("Description");
        }
        /// <summary>
        /// Links the button country click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButtonCountryClick(object sender, EventArgs eventArgs)
        {
            Sorting("CountryName");
        }
        /// <summary>
        /// Links the button status click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButtonStatusClick(object sender, EventArgs eventArgs)
        {
            Sorting("IsActive");
        }
        protected void LinkButton1Click(object sender, EventArgs e)
        {
            LoadTrustRegion(CheckBoxIncludeInactive.Checked);
            RemoveActiveOnButton();
            LinkButton1.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button2 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton2Click(object sender, EventArgs e)
        {
            FilterTrustRegion(CheckBoxIncludeInactive.Checked, "0123456789");
            RemoveActiveOnButton();
            LinkButton2.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button3 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton3Click(object sender, EventArgs e)
        {
            FilterTrustRegion(CheckBoxIncludeInactive.Checked, "ABCDE");
            RemoveActiveOnButton();
            LinkButton3.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button4 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton4Click(object sender, EventArgs e)
        {
            FilterTrustRegion(CheckBoxIncludeInactive.Checked, "FGHIJ");
            RemoveActiveOnButton();
            LinkButton4.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button5 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton5Click(object sender, EventArgs e)
        {
            FilterTrustRegion(CheckBoxIncludeInactive.Checked, "KLMN");
            RemoveActiveOnButton();
            LinkButton5.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button6 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton6Click(object sender, EventArgs e)
        {
            FilterTrustRegion(CheckBoxIncludeInactive.Checked, "OPQR");
            RemoveActiveOnButton();
            LinkButton6.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button7 click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton7Click(object sender, EventArgs e)
        {
            FilterTrustRegion(CheckBoxIncludeInactive.Checked, "STUV");
            RemoveActiveOnButton();
            LinkButton7.CssClass = "button-active";
        }
        /// <summary>
        /// Links the button8 C lick.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LinkButton8Click(object sender, EventArgs e)
        {
            FilterTrustRegion(CheckBoxIncludeInactive.Checked, "WXYZ");
            RemoveActiveOnButton();
            LinkButton8.CssClass = "button-active";
        }
        /// <summary>
        /// Buttons the creat click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonCreatClick(object sender, EventArgs e)
        {
            Response.Redirect("RegionDetail.aspx");
        }
        /// <summary>
        /// Repeaters the item click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void RepeaterItemClick(object sender, RepeaterCommandEventArgs eventArgs)
        {
            var hiddenField =
                RepeaterTrustRegion.Items[eventArgs.Item.ItemIndex].FindControl("HiddenFieldStatus") as HiddenField;
            if (hiddenField != null)
            {
                var values = hiddenField.Value.Split('$');
                string status = values[0].ToString(_formatProvider);
                int trustRegionId = int.Parse(values[1].ToString(_formatProvider), _formatProvider);
                _trustRegionId = trustRegionId;
                if (eventArgs.CommandName == "click")
                {
                    if (status == "No")
                    {
                        var jsScript = new StringBuilder();
                        jsScript.AppendFormat("var foo = window.confirm('Do you want to make this Trust Region active?');\n");
                        jsScript.Append("if (foo)\n");
                        jsScript.Append("__doPostBack('MyConfirmationPostBackEventTarget', foo);\n");
                        ScriptManager.RegisterStartupScript(UpdatePanelListRegion, GetType(), "confirm", jsScript.ToString(), true);
                    }
                    else
                    {
                        Response.Redirect("RegionDetail.aspx?TrustRegionId=" + trustRegionId);
                    }
                }
            }
        }
        #endregion
    }
}